#!/usr/bin/python3

"""
下载破晓电影
"""
from down_dybee_film import dybee
import zjl_util
import uapool
import re
import getopt
import sys


class DownPoxiao():
    def __init__(self, header_file_path, dir_path):
        self.header_file_path = header_file_path
        self.dir_path = dir_path

    def down(self, index_url, offset: 0):
        m3u8_list = self.get_video_m3u8_url_and_name(index_url)
        d = dybee()
        for i in range(offset, len(m3u8_list)):
            info = m3u8_list[i]
            m3u8_url = info[0]
            file_name = info[1] + '.ts'
            d.set_header(self.header_file_path, m3u8_url)
            print('开始下载 ... \nm3u8:' + m3u8_url + ', dir_path:' + self.dir_path + ', file_name:' + file_name)
            d.down_file(m3u8_url, self.dir_path, file_name)

    def get_video_m3u8_url_and_name(self, index_url):
        uapool.UA()
        doc = zjl_util.get_doc(index_url)
        pat = '<ul class="stui-content__playlist.*?</ul>'
        r = re.compile(pat, re.S).findall(doc)
        if len(r) == 0:
            print('[warn] not foud video list')
            return []
        list_html = r[len(r) - 1]
        a_pat = '<a href="(.*?)">(.*?)</a>'
        url_and_name_s = re.compile(a_pat, re.S).findall(list_html)
        base_url = uapool.get_base_url(index_url)
        r_idx = index_url.rindex('/')
        refer_url = index_url[0: (r_idx + 1)]
        r = []
        for i in url_and_name_s:
            video_url = i[0]
            file_name = i[1]
            if str(video_url).startswith('/'):
                video_url = base_url + video_url
            elif str(video_url).startswith('http'):
                print('')
            else:
                video_url = refer_url + video_url
            """ 然后准备获取视频的m3u8地址 """
            doc = zjl_util.get_doc(video_url)
            # print(doc)
            m3u8_pat = 'player_data=\{.*?"url":"(.*?\.m3u8)'
            m3u8_r = re.compile(m3u8_pat, re.S).findall(doc)
            if len(m3u8_r) == 0:
                print('[warn]: ' + video_url + ' not found m3u8 url')
                continue
            first_m3u8_url = str(m3u8_r[0]).replace('\\', '')
            m3u8_doc = zjl_util.get_doc(first_m3u8_url)
            m3u8_pat = '(.*?\.m3u8)'
            m3u8_uri_s = re.compile(m3u8_pat).findall(m3u8_doc)
            m3u8_url = first_m3u8_url[0: (first_m3u8_url.rindex('/') + 1)] + m3u8_uri_s[0]

            info = [m3u8_url, file_name]
            print(info)
            r.append(info)
        return r


def main():
    index_url = 'http://www.poxiaotv.com/vodhtml/52254.html'
    dir_path = 'd:/video/缘之空'
    header_file_path = 'D:/test/film/header.conf'
    offset = 0

    opts, args = getopt.getopt(sys.argv[1:], "hu:d:H:o:")
    for o, a in opts:
        if o == '-h':
            print("python3 down_poxiao.py -u " + index_url + " -d " + dir_path + " -H " + str(header_file_path)
                  + " -o " + str(offset))
            exit()
        if o == '-u':
            index_url = a
        if o == '-o':
            offset = int(a)
        if o == '-d':
            dir_path = a
        if o == '-H':
            header_file_path = a
    print('目录地址：' + index_url)
    print('保存路径：' + dir_path)
    d = DownPoxiao(header_file_path, dir_path)
    d.down(index_url, offset)


if __name__ == "__main__":
    main()
